#include "httpserver.h"

#include <QSqlQuery>



// 假设你的库存系统已有以下功能函数（需提前实现）
int getStockFromDB(const QString &productId) {
    // 示例：从数据库查询库存（实际替换为你的逻辑）
    QSqlQuery query;
    QString sql = QString("SELECT stock_amount FROM commodity_data WHERE stock_id = %1").arg(productId);

    if (query.exec(sql) && query.next()) {
        return query.value("stock_amount").toInt();
    }
    return -1;  // 未找到商品
}

bool updateStockInDB(const QString &productId, int newStock) {
    // 示例：更新数据库库存（实际替换为你的逻辑）
    QSqlQuery query;
    QString sql = QString("UPDATE commodity_data SET stock_amount = %1 WHERE stock_name = '%2'").arg(newStock).arg(productId);
    qDebug() << sql;

    return query.exec(sql);
}
HttpServer::HttpServer()
{

    // 启动服务器，监听  端口
    if (!listen(QHostAddress::Any, 8080)) {
        qDebug() << "服务器启动失败！";
    } else {
        qDebug() << "HTTP 服务器已启动，监听端口：8080";
    }


}

//处理新连接
void HttpServer::incomingConnection(qintptr socketDescriptor)
{
    // 创建 socket 处理新连接
    QTcpSocket *socket = new QTcpSocket(this);
    //而 socket->setSocketDescriptor(socketDescriptor) 就像给这个客人 “分配座位” 的操作：
    //把号码牌（socketDescriptor）和餐厅里的一张具体桌子（QTcpSocket 对象）绑定，
    //这样后续服务员（程序逻辑）就能通过这张桌子和客人沟通（收发数据
    if (!socket->setSocketDescriptor(socketDescriptor)) {
        qDebug() << "连接失败！";
        return;
    }
    qDebug() << "连接成功！";
    connect(socket, &QTcpSocket::readyRead, this, &HttpServer::handleRequest);
}


//只要QTcpSocket有数据可读，就调用这个函数
void HttpServer::handleRequest()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket) return;

    // 读取所有请求数据
//    QByteArray requestData = socket->readAll();
//    QString request = QString::fromUtf8(requestData);
//    qDebug() << "handleRequest的request=" << request;

    // 解析请求
    QString method, path, body;
    QMap<QString, QString> params;
    parseHttpRequest(socket, method, path, params, body);

    // 根据路径处理请求（路由逻辑）
        QByteArray responseBody;
        int statusCode = 200;
        QString contentType = "application/json";

        if (path == "/api/getStock" && method == "GET") {
            // 处理 GET /api/getStock（查询库存）
            QString productId = params.value("stock_id");
            qDebug() << "productId=" << productId;
            if (productId.isEmpty()) {
                statusCode = 400;
                responseBody = QJsonDocument(
                    QJsonObject{{"code", 400}, {"message", "缺少 productId 参数"}}
                ).toJson();
            } else {
                int stock = getStockFromDB(productId);
                if (stock == -1) {
                    statusCode = 404;
                    responseBody = QJsonDocument(
                        QJsonObject{{"code", 404}, {"message", "商品不存在"}}
                    ).toJson();
                } else {
                    responseBody = QJsonDocument(
                        QJsonObject{{"code", 200}, {"productId", productId}, {"stock", stock}}
                    ).toJson();
                }
            }
        } else if (path == "/api/updateStock" && method == "POST") {
            // 处理 POST /api/updateStock（修改库存）
            QJsonParseError parseError;
            QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8(), &parseError);
            if (parseError.error != QJsonParseError::NoError) {
                statusCode = 400;
                responseBody = QJsonDocument(
                    QJsonObject{{"code", 400}, {"message", "JSON 格式错误"}}
                ).toJson();
            } else {
                QJsonObject json = doc.object();
                QString productId = json["stock_name"].toString();
                int newStock = json["stock_amount"].toInt();
                if (productId.isEmpty() || newStock < 0) {
                    statusCode = 400;
                    responseBody = QJsonDocument(
                        QJsonObject{{"code", 400}, {"message", "参数错误"}}
                    ).toJson();
                } else {
                    bool success = updateStockInDB(productId, newStock);
                    responseBody = QJsonDocument(
                        QJsonObject{{"code", success ? 200 : 500},
                                    {"message", success ? "修改成功" : "修改失败"}}
                    ).toJson();
                }
            }
        } else {
            // 路径不存在
            statusCode = 404;
            responseBody = QJsonDocument(
                QJsonObject{{"code", 404}, {"message", "接口不存在"}}
            ).toJson();
        }

        // 发送响应
        sendResponse(socket, statusCode, contentType, responseBody);
        socket->disconnectFromHost();  // 短连接，处理完关闭
}

//解析 HTTP 请求（返回方法、路径、参数、请求体）
void HttpServer::parseHttpRequest(QTcpSocket *socket, QString &method, QString &path, QMap<QString, QString> &params, QString &body)
{
    QByteArray requestData = socket->readAll();
    QString request = QString::fromUtf8(requestData);
    qDebug() << "request=" << request;

    // 解析请求行（第一行：方法 路径 HTTP/版本）
    QStringList lines = request.split("\r\n");

    //测试
    for(const auto line:lines)
    {
        qDebug() << "line=" << line;
    }

    if (lines.isEmpty()) return;
    QString requestLine = lines.first();
    qDebug() << "requestLine=" << requestLine;
    QStringList requestParts = requestLine.split(" ");

    //测试
    for(const auto part:requestParts)
    {
        qDebug() << "part=" << part;
    }
    qDebug() << "requestParts的长度="<< requestParts.size();

    if (requestParts.size() < 3) return;
    method = requestParts[0].toUpper();  // GET/POST
    QString fullPath = requestParts[1];  // 如 "/api/getStock?productId=123"

    // 解析路径和查询参数（GET）
        int queryIndex = fullPath.indexOf('?');
        qDebug() << queryIndex;
        if (queryIndex != -1) {
            path = fullPath.left(queryIndex);
            QString queryString = fullPath.mid(queryIndex + 1);
            qDebug() << "queryString=" << queryString;
            QUrlQuery query(queryString);
            for (const auto &pair : query.queryItems()) {
                params[pair.first] = pair.second;
            }
        } else {
            path = fullPath;
        }

        // 解析请求体（POST）
        if (method == "POST") {
            // 找到头部结束标记（空行 "\r\n\r\n"）
            int bodyIndex = request.indexOf("\r\n\r\n");
            if (bodyIndex != -1) {
                body = request.mid(bodyIndex + 4);  // 正文内容
            }
        }
}

void HttpServer::sendResponse(QTcpSocket *socket, int statusCode, const QString &contentType, const QByteArray &body)
{
    QString statusText;
        switch (statusCode) {
            case 200: statusText = "OK"; break;
            case 400: statusText = "Bad Request"; break;
            case 404: statusText = "Not Found"; break;
            case 500: statusText = "Internal Server Error"; break;
            default: statusText = "Unknown";
        }

        // 构造 HTTP 响应头
        QByteArray response;
        response += QString("HTTP/1.1 %1 %2\r\n").arg(statusCode).arg(statusText);
        response += QString("Content-Type: %1; charset=utf-8\r\n").arg(contentType);
        response += QString("Content-Length: %1\r\n").arg(body.size());
        response += "Access-Control-Allow-Origin: *\r\n";  // 允许跨域
        response += "\r\n";  // 头部结束
        response += body;    // 正文

        socket->write(response);
        socket->flush();
}
